package com.mylibraryapplication.adapter;

import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.mylibrary.util.AbViewUtil;
import com.mylibrary.view.tabIndicator.IndicatorViewPager;
import com.mylibraryapplication.R;
import com.mylibraryapplication.TabFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yinsujun  Created at 2016/7/27 18:08
 */
public class TabIndicatorAdapter  extends IndicatorViewPager.IndicatorFragmentPagerAdapter{
    private Context context;
    private String[] titles={"标题1","标题2","你够了,小朋友","标题4","没创意~~~","标题长长长长长长长长长长长长·····"};
    private List<Fragment> fragments=new ArrayList<>();
    public TabIndicatorAdapter(FragmentManager fragmentManager,Context context) {
        super(fragmentManager);
        this.context=context;
        initFragment();
    }
    private void initFragment(){
        for(int i=0;i<titles.length;i++){
            TabFragment tabFragment=new TabFragment();
            Bundle bundle=new Bundle();
            bundle.putString("title",titles[i]);
            tabFragment.setArguments(bundle);
            fragments.add(tabFragment);
        }
    }

    @Override
    public int getCount() {
        return titles.length;
    }

    @Override
    public View getViewForTab(int position, View convertView, ViewGroup container) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.tab_top, container, false);
        }
        TextView textView = (TextView) convertView;
        textView.setText(titles[position]);

        int with = getTextWidth(textView);
        int padding = AbViewUtil.dip2px(context, 8);
        //因为wrap的布局 字体大小变化会导致textView大小变化产生抖动，这里通过设置textView宽度就避免抖动现象
        //1.3f是根据上面字体大小变化的倍数1.3f设置
        textView.setWidth((int) (with * 1.3f) + padding);
        return convertView;
    }

    @Override
    public Fragment getFragmentForPage(int position) {
        return fragments.get(position);
    }
    private int getTextWidth(TextView textView) {
        if (textView == null) {
            return 0;
        }
        Rect bounds = new Rect();
        String text = textView.getText().toString();
        Paint paint = textView.getPaint();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int width = bounds.left + bounds.width();
        return width;
    }
}
